package com.lx.idgenerator.lifecycle;

import com.lx.idgenerator.exception.BizException;

/**
 * 抽象生命周期管理方法,state不可重复
 * @author lX
 * @version JDK 8
 * @className AbstractGeneratorLifecycle (此处以class为例)
 * @date 2024/10/28
 * @description TODO
 */
public class AbstractGeneratorLifecycle  implements  IIDGeneratorLifecycle{

    public static final String MSG_FORMAT = "前一个状态必须为: %s,当前为: %s";

    /**
     * 组件默认状态
     */
    protected GeneratorState state = GeneratorState.DEFAULT_STATE;
    @Override
    public void init() {

        //检查状态
        checkState(GeneratorState.DEFAULT_STATE);


        //真正初始化方法由子类创建
        doInit();

        //初始化完成修改状态
        state = GeneratorState.INIT_STATE;

    }


    protected void doInit(){

    }

    @Override
    public void start() {

        //检查状态
        checkState(GeneratorState.INIT_STATE);

        doStart();

        state = GeneratorState.START_STATE;

    }

    /**
     * 状态检查
     * @param expectState 期待的当前状态
     */
    private  void  checkState(GeneratorState expectState){

        if (getState() != expectState) {
            throw new BizException(String.format(MSG_FORMAT, expectState.getDesc(), getState().getDesc()));
        }

    }

    protected void doStart(){

    }

    @Override
    public void stop() {
        checkState(GeneratorState.START_STATE);
        doStop();
        state = GeneratorState.STOP_STATE;
    }

    protected void doStop(){

    }

    @Override
    public String name() {
        return null;
    }

    @Override
    public GeneratorState getState() {
        return state;
    }
}
